package com.bree.erp.jsf.view;


import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;

import com.bree.erp.entity.Inventory;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.jsf.datatable.LazyBreeDataModel;
import com.bree.erp.jsf.vo.InventoryDT;
import com.bree.erp.service.InventoryService;
import com.bree.erp.service.InventoryWrapperService;
import com.bree.erp.service.MasterItemService;

@ManagedBean(name="dtInventoryLazyView")
@ViewScoped
public class InventoryLazyView {

	private static Logger LOG = Logger.getLogger(InventoryLazyView.class);

    private LazyDataModel<InventoryDT> lazyModel;
    
    @EJB
    private InventoryWrapperService invService;
    
    @EJB
    private MasterItemService miService;

	private InventoryDT selectedItem;

    @PostConstruct
    public void init() {
    	lazyModel = new LazyBreeDataModel<InventoryDT, InventoryWrapperService, String>(invService, "");
    }


	public LazyDataModel<InventoryDT> getLazyModel() {
				
        return lazyModel;
    }
 
    public InventoryDT getSelectedItem() {
        return selectedItem;
    }
 
    public void setSelectedItem(InventoryDT selectedItem) {
        this.selectedItem = selectedItem;
        
    }
     
    public void onRowSelect(SelectEvent event) {
        FacesMessage msg = new FacesMessage("Item Selected", ((MasterItem) event.getObject()).getId() + "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
    
    public void initData() {
    	
    	LOG.debug("initializing inventory data...");
    	
    	Collection<MasterItem> masterItems = miService.list();
    	for(MasterItem masterItem : masterItems) {
    		if(masterItem.getInventory() == null) {
    			LOG.debug("init inventory for: " + masterItem.getId());
    			invService.create(masterItem);
    		} else {
    			LOG.warn("masterItem " + masterItem.getId() + " is not empty!");
    		}
    	}
    }

}
